
var apiPath = './api.php';
window.log = function() {
	var al = arguments;
	console.log(...al)
}
window.__copy = function (data) {
	var copy = JSON.parse(JSON.stringify(data));
	return copy;
}
window.__ss = function (k,v) {
	if (k) {
		sessionStorage.setItem(k,v);
	}
}
window.__ls = function (k,v) {
	if (k) {
		localStorage.setItem(k,v);
	}
}
window.__gss = function (k) {
	if (k) return sessionStorage.getItem(k);
	return sessionStorage
}
window.__gls = function (k) {
	if (k) return localStorage.getItem(k);
	return localStorage
}
window.__url = function (k) {
	return apiPath;
}
window.__fmData = function (l,f) {
	let isArray = function(val) { return toString.call(val) === '[object Array]'; }
	let arr = [];
	let arr0= Object.create(f)
	if (isArray(l)) {
		for (let i = 0; i < l.length; i++) {
			let item =  [];
			let data = l[i];
			for (let j = 0; j < f.length; j++) {
				let obj = Object.create(f[j])
				let opt = f[j].options || [];
				let k = f[j].key;
				let val  = '';
				let value  = '';
				if (data[k] || (data[k] === 0)) {
					value = data[k];
					val   = data[k];
				}
				let stype = f[j].srcType || 'text'
				let dtype = f[j].type
				if ((stype == 'number') && (dtype == 'dateTime')) {
					if (value < 2000000000) value *= 1000;
					var date = new Date(parseFloat(value));
					if (date) val = __ymdHis(date);
				}
				if (dtype == 'select') {
					for (let oi = 0; oi < opt.length; oi++) if (opt[oi].v == value) val = opt[oi].k
				}
				if (dtype == 'color') {
					for (let oi = 0; oi < opt.length; oi++) if (opt[oi].v == value) {
						val = '<div class="wh15 br10 disi" style="background-color:'+opt[oi].k+';" ></div>'
					}
				}
				obj.val   = val;
				obj.value = value;
				item.push(obj)
			}
			arr.push(item)
		}
	}
	return arr;
}
window.__app = {};
window.__router = {};
if (!window.routes) window.routes = [];

var __widget = [
	{
		name: 'App',
		template: `
		<div class="wh100 pr ofh trs2" name="main" :style="{'opacity': opacity}">
		<transition name="slide-fade">
			<router-view></router-view>
		</transition >
		<div v-if="isAdmin" name="tool-box" class="pf t0 r0 hovchh30">
			<div class="pdtb5 pd05 hovchh30_ch ofh">
				<div class="wh30 btn bg01 opa5 trs2 hovopa1" @click="openSetting">
					<i class="fa fa-th"></i>
				</div>
			</div>
		</div>
		<transition name="slide-fade">
			<router-list v-if="setting" v-model="setting"></router-list>
		</transition >
	  	</div>`,
		data: function () {
			return {
				opacity: 0,
				setting: false,
				isAdmin: false,
			}
		},
		methods: {
			openSetting(){this.setting = true;},
			getList() {
				let v = this;
				let data = {action:'query',data:{where:{eq:{b:1,c:2}}},desc:'get-menu'};
				__post(apiPath,data).then(function(r) {
					let l = r.data;
					let a = [];
					for (let i in l) {
						let name = l[i].f || '';
						if (name[0] == '/') name = name.substr(1);
						let component = {
							name: name,
							template: l[i].g,
						}
						let it = {
							path: l[i].f,
							name: name,
							component: component,
						};
						if (it.component) a.push(it);
						// __router.addRoute(it);
					}
				})
			},
		},
		created: function () {
			let v = this;
			v.opacity = 1;
			v.getList('menu');
		},
	},
	{
		name: 'FormData',
		template: `
		<div class="form-inst" :class="pclass" name="FormData-inst" >
		<form class="form pd05 flex flw bgf lh25"  >
			<div v-for="(v,k) in value" class="form-row pd5 miw300 flex bbx" :class="[v.t == 'textarea' ? 'w100' : 'miw300']" >
				<div name="label" class="bbx pd05 right miw101 w101 flec c333" ><span v-html="v.k"></span></div>
				<div name="input-box" class="bbx pd05 flex1">
					<Input :type="v.t" :class="[v.ic?v.ic:dic]" v-model="v.v" @change="doUpdate(v,k)" />
				</div>
				<div v-if="v.t == 'textarea'" class="w40" name="padding-right"></div>
			</div>
		</form>
	  	</div>`,
	  	props: {
	  		value: { type: Array,default: []},
	  		class: { type: String,default: ''},
	  	},
		data: function () {
			return {
				fmta: [],
				list: [],
				pclass: '',
				dic: 'h30',
			}
		},
		watch:{
			'value' () {this.setData();},
		},
		methods: {
			setData(){
				let v = this;
				v.pclass = v.class;
			},
			doUpdate(i,k){
				let v = this;
				let t = __copy(v.value);
				t[k].v = i.v;
				v.$emit('input',t);
			},
		},
		created: function () {
			let v = this;
			v.setData();
		},
	},
	{
		name: 'EditForm',
		template: `
		<div class="form-inst" :class="pclass" name="EditForm-inst" >
		<form class="form pd05 flex flw bgf lh25"  >
			<div v-for="(v,k) in fmta" class="form-row pd5 miw300 flex bbx" :class="[v.t == 'textarea' ? 'w100' : 'miw300']" >
				<div name="label" class="bbx pd05 right miw101 w101" ><span v-html="v.k"></span></div>
				<div name="input-box" class="bbx pd05 flex1">
					<Input :type="v.t" :class="v.ic" v-model="v.v" @change="doUpdate(v,k)" />
				</div>
				<div v-if="v.t == 'textarea'" class="w40" name="padding-right"></div>
			</div>
		</form>
	  	</div>`,
	  	props: {
	  		value: { type: Array,default: []},
	  		fmt: { type: Array,default: []},
	  		class: { type: String,default: ''},
	  	},
		data: function () {
			return {
				fmta: [],
				list: [],
				pclass: '',
			}
		},
		watch:{
			'value' () {this.setData();},
		},
		methods: {
			setData(){
				let v = this;
				let f = [];
				let l = [];
				let c = 0;
				for (let k in v.value){
					let fi = {t:'text',k:'',v:'',l:[],c:'',key:''}
					let fk = parseInt(k);
					if (v.fmt[c] && v.fmt[c].t) fi.t = v.fmt[c].t;
					if (v.fmt[c] && v.fmt[c].ic) fi.ic = v.fmt[c].ic;
					fi.k   = v.fmt[c].k || k || fk;
					fi.key = k;
					fi.v   = v.value[k];
					f.push(fi);
					c++;
				}
				v.fmta = f;
				v.list = l;
				v.pclass = v.class;
			},
			doUpdate(i,k){
				let v = this;
				let t = __copy(v.value);
				t[i.k] = i.v;
				v.$emit('input',t);
			},
		},
		created: function () {
			let v = this;
			v.setData();
		},
	},
	{
		name: 'routerList',
		template: `
		<div class="pf z2 t0 l0 wh100 ofh trs2 bgf" name="router-list" >
		<div class="wh100 " name="panel">
			<div class="w100 bbx">
				<div class="w100 pd020 pdt20">
					<div class="center pdtb10 lh30 sp1">
						<div class="fs16">设置</div>
					</div>
					<Table :tbody="dataList" :thead="dataHead" :enadc="[1,0,1,0]" class="thbdlr w100 ofh center lh30"
						@edit="doEdit" @add="doAdd" @del="doDel"></Table>
				</div>
			</div>
		</div>
		<div name="modal">
			<Modal v-model="editModal" @ok="doSaveEdit" @cancel="editModal = false"
				okText = "保存" cancelText="取消" width="500" title="修改">
				<EditForm v-model="editItem" :fmt="fmt" class="lh25"></EditForm>
			</Modal>
			<Modal v-model="addiModal" @ok="doSaveAddi" @cancel="addiModal = false"
				okText = "保存" cancelText="取消" width="500" title="添加">
				<EditForm v-model="editItem" :fmt="fmt" class="lh25"></EditForm>
			</Modal>
		</div>
		<div name="close-box" class="pf t5 r5">
			<div class="wh30 btn bg01 opa8 trs2 hovopa1" @click="openSetting">
				<i class="fa fa-close"></i>
			</div>
		</div>
	  	</div>`,
	  	props: {
	  		value: { type: Boolean,default: false},
	  	},
		data: function () {
			return {
				opacity: 0,
				setting: false,
				dataList: [],
				dataHead: [],
				editModal: false,
				addiModal: false,
				deliModal: false,
				editItem: [],
				fmt:[
					{t:'number',ic:'h30'},
					{t:'number',ic:'h30'},
					{t:'number',ic:'h30'},
					{t:'number',ic:'h30'},
					{t:'number',ic:'h30'},
					{t:'textarea'},
					{t:'textarea'},
				],
				id:1,
			}
		},
		methods: {
			openSetting(){
				let val = !this.value;
				this.$emit('input',val);
			},
			getList() {
				let v = this;
				__post(apiPath).then(function(r) {
					let l = r.data;
					let a = [];
					for (let i in l) {
						for (let n in l[i]) a.push(n);
						break;
					}
					v.dataList = l;
					v.dataHead = a;
					v.id = r.count;
					return 
				}).catch(function(err) {
					log('catch',err);
				});
			},
			doAdd(){
				let v = this;
				let i = {a:v.id + 1,b:'',c:'',d:'',e:'',f:'',g:'',};
				v.editItem = i;
				v.addiModal = true;
			},
			doSaveAddi(){
				let v = this;
				let d = {};
				for (let k in v.editItem) if (v.editItem[k] || v.editItem[k] == '' || v.editItem[k] == 0) {
					d[k] = v.editItem[k];
				}
				let data = {action: 'insert',data:d,}
				__post(apiPath,data).then((r)=> {
					if (r.code === 200) {
						v.getList();
						v.addiModal = false;
						__msg(r,data);
					}
				})
			},
			doEdit(r,i){
				let v = this;
				v.editItem = __copy(r);
				v.editModal = true;
			},
			doSaveEdit(){
				let v = this;
				let d = {};
				for (let k in v.editItem) if (v.editItem[k] || v.editItem[k] == '' || v.editItem[k] == 0) {
					d[k] = v.editItem[k];
				}
				let data = {action: 'update',data:d,}
				__post(apiPath,data).then((r)=> {
					if (r.code === 200) {
						v.getList();
						v.editModal = false;
						__msg(r,data);
					}
				})
			},
			doDel(r,i){
				let v = this;
				v.editItem = __copy(r);
				__confirm('<font color="red">您确定要删除吗？<font>',500000).then((r)=>{
        			console.log('delDataItem');
        			v.doSaveDeli();
        		})
			},
			doSaveDeli(){
				let v = this;
				let d = {};
				for (let k in v.editItem) if (v.editItem[k] || v.editItem[k] == '' || v.editItem[k] == 0) {d[k] = v.editItem[k];break;}
				let data = {action: 'delete',data:d,}
				__post(apiPath,data).then((r)=> {
					if (r.code === 200) {
						v.getList();
						__msg(r,data);
					}
				})
			},
		},
		created: function () {
			let v = this;
			v.getList()
		},
	},
	{
		name: 'Layout',
		template: `
		<div :id="eid" name="layout-i" :class="pclass" :style="styles" @mousedown="selected">
			<div class="pa z2 t0 l0 r0 h35 cm flec bg01">
				<div class="h100 flex1 ofh flec" @mousedown="mousedown($event,1)">
					<div class="w100 txt pd05 left" v-text="value.k" :title="value.k"></div>
				</div>
				<div class="h100 flec lh25">
					<div v-if="enResize" class="wh30 btn hovbg03" @click="setPos(0)"><i class="fa fa-window-restore" ></i></div>
					<div v-if="enResize" class="wh30 btn hovbg03" @click="setPos(1)"><i class="fa fa-window-maximize" ></i></div>
					<div v-if="enSet" class="wh30 btn hovbg03"><i class="fa fa-cog"></i></div>
				</div>
			</div>
			<div name="l-i-box" class="z1 wh100 pr ">
				<component v-if="value.component" :key="value.k" ref="component" :is='value.component' ></component>
				<div v-if="enResize">
					<div class="pa b0px r0px w40 h40 trs2 bdrb5 hbdci cmse" action-dir
					v-if="pos.l && pos.t" @mousedown="mousedown($event,2)" >
					</div>
					<div class="pa b0px l0px w40 h40 trs2 bdlb5 hbdci cmsn"
					v-if="pos.r && pos.t" @mousedown="mousedown($event,3)" >
					</div>
					<div class="pa t0px r0px w40 h40 trs2 bdrt5 hbdci cmsn" 
					v-if="pos.l && pos.b" @mousedown="mousedown($event,4)" >
					</div>
					<div class="pa t0px l0px w40 h40 trs2 bdlt5 hbdci cmse "
					v-if="pos.r && pos.b" @mousedown="mousedown($event,5)" >
					</div>
					<div class="pa t20px b20px r0px w5 trs2 bdrr5 hbdci cmw "
					v-if="pos.l && pos.t" @mousedown="mousedown($event,6)" >
					</div>
				</div>
			</div>
	  	</div>`,
	  	props: {
	  		value: { type: Object,default: {}},
	  		class: { type: String,default: ''},
	  		active: { type: Boolean,default: false},
	  	},
		data: function () {
			return {
				eid: 'layout',
				list: [],
				styles: {},
				useAnchor: false,
				useBorder: true,
				enResize: true,
				enSet: false,
				action: 0,
				rect:{},
				dragging: false,
				resizing: false,
				dragData:{x:0,y:0,_x:0,_y:0,w:0,h:0,mx:0,my:0},
				pos:{},
				last: {},
				zIndex: 1,
			}
		},
		watch:{'value' () {this.setLayout();},},
		computed: {
			pclass (){return [this.class,'bbx',this.useAnchor?'pa':'pr',this.useBorder?'hovbdci bd1c':'',this.active?'z2':'z1']},
		},
		created: function (v = this) {
			v.eid = 'widget_' + __getid();
		},
		mounted (v = this) {
			v.setLayout();
		},
		methods: {
			selected () {this.$emit('click');},
			setLayout(v = this){
				v.getStyle();
			},
			setPos (k,v = this) {
				if (k) {
					v.$emit('maxsize');
				} else {
					v.$emit('minsize');
					
				}
				v.getStyle();
			},
			getStyle (v = this,d = v.value,p = v.value.pos) {
				let si = {t:0,r:0,b:0,l:0,w:0,h:0,z:1,d:'row',av:'center',ah:'center',};
				for (let k in si) if (p[k] !== undefined) si[k] = p[k];
				if (!si.t && !si.r && !si.b && !si.l) {v.useAnchor = false} else {v.useAnchor = true};
				let tf = false;
				for (let k in si) if (si[k] !== v.pos[k]) tf = false;
				if (!tf) v.last = __copy(si);
				v.pos = si;
				v.styles = v.getStyles(si);
			},
			mousedown (e,act,v = this) {
        		if (!v.enResize) return;
        		v.action = act;
        		let el = document.getElementById(v.eid);
                let rect = el.getBoundingClientRect();
        		let bx = el.parentElement;
                let rc   = bx.getBoundingClientRect();
                v.rect   = rc;
                let scrollY = 0;
                if (bx.scrollTop > 0) {scrollY = bx.scrollTop; }
                v.dragData.x  = rect.left  - rc.left;
                v.dragData.y  = rect.top   - rc.top      + scrollY;
                v.dragData.w = rect.width;
                v.dragData.h = rect.height;
                v.dragData.mx = e.clientX;
                v.dragData.my = e.clientY;
                v.dragging = (act == 1);
                v.resizing = (act > 1);
                v.pos.l = v.dragData.x  + 'px';
                v.pos.t = v.dragData.y  + 'px';
                v.pos.w = v.dragData.w  + 'px';
                v.pos.h = v.dragData.h  + 'px';
                v.useAnchor = true;
                console.log('rect',v.pos)
                v.updateItemPosition();
                __on(window, 'mousemove', v.handleMoveMove);
                __on(window, 'mouseup',   v.handleMoveEnd );
            },
            handleMoveMove (e,v = this) {
                if (v.dragging) {
                	const distance = { x: e.clientX, y: e.clientY };
	                const diff_distance = { x: distance.x - v.dragData.mx, y: distance.y - v.dragData.my};
	                v.dragData.x += diff_distance.x;
	                v.dragData.y += diff_distance.y;
	                v.dragData.mx = distance.x;
	                v.dragData.my = distance.y;
	                v.updateItemPosition();
                } else {
                	const distance = { x: e.clientX, y: e.clientY };
	                const diff_distance = { x: distance.x - v.dragData.mx, y: distance.y - v.dragData.my};
	                v.dragData.mx = distance.x;
	                v.dragData.my = distance.y;
	                switch (v.action) {
	                	case 2: {
	                		v.dragData.w += diff_distance.x;
	                		v.dragData.h += diff_distance.y;
	                		break;
	                	}
	                	case 3: {
	                		v.dragData.w -= diff_distance.x;
		            		v.dragData.h += diff_distance.y;
	                		break;
	                	}
	                	case 4: {
	                		v.dragData.w += diff_distance.x;
		            		v.dragData.h -= diff_distance.y;
	                		break;
	                	}
	                	case 5: {
	                		v.dragData.w -= diff_distance.x;
		            		v.dragData.h -= diff_distance.y;
	                		break;
	                	}
	                	case 6: {
	                		v.dragData.w += diff_distance.x;
	                		break;
	                	}
	                }
	                v.updateItemSize();
	                return
	                if(v.action === 2) {
                		v.dragData.w += diff_distance.x;
	                	v.dragData.h += diff_distance.y;
                	}
                	if(v.action === 3) {
                		v.dragData.w -= diff_distance.x;
		            	v.dragData.h += diff_distance.y;
                	}
                	if(v.action === 4) {
                		v.dragData.w += diff_distance.x;
		            	v.dragData.h -= diff_distance.y;
                	}
                	if(v.action === 5) {
                		v.dragData.w -= diff_distance.x;
		            	v.dragData.h -= diff_distance.y;
                	}
                	if(v.action === 6) {
                		v.dragData.w += diff_distance.x;
                	}
	                v.updateItemSize();
	                return
                }
            },
            updateItemPosition (v = this,i = v.pos) {
            	let style = {};
            	// console.log('updateItemPosition',i.l,i.t,i.r,i.b,'xy',v.dragData.x,v.dragData.y)
            	if (i.l) {
            		style.left = `${this.dragData.x}px`;
            		if (i.l.indexOf('%') > -1) style.left = (100*v.dragData.x/v.rect.width).toFixed(4) + '%';
            		i.l = style.left;
            	} else if (i.r) {
            		style.right = `${this.dragData.x}px`;
            		if (i.r.indexOf('%') > -1) style.right = (100*v.dragData.z/v.rect.width).toFixed(4) + '%';
            		i.r = style.right;
            	}
            	if (i.t ) {
            		style.top  = `${this.dragData.y}px`;
            		if (i.t.indexOf('%') > -1) style.top = (100*v.dragData.y/v.rect.height).toFixed(4) + '%';
            		i.t  = style.top;
            	} else if (i.b) {
            		style.bottom  = `${this.dragData.y}px`;
            		if (i.b.indexOf('%') > -1) style.bottom = (100*v.dragData.w/v.rect.height).toFixed(4) + '%';
            		i.b  = style.bottom;
            	}
            	v.styles = v.getStyles(i);
            },
            updateItemSize (v = this,i = v.pos) {
            	//console.log('updateItemSize',i.l,i.t,i.r,i.b,'xy',v.dragData.x,v.dragData.y,'wh',v.dragData.w,v.dragData.h)
            	let style = {};
            	if (i.w) {
            		style.width = `${this.dragData.w}px`;
            		if (i.w.indexOf('%') > -1) style.width = (100*v.dragData.w/v.rect.width).toFixed(4) + '%';
            		if (i.l && i.r) i.right = '';
            		i.w = style.width;
            	} else {
            		style.width = (100*v.dragData.w/v.rect.width).toFixed(4) + '%';
            		i.w = style.width;
            	}
            	if (i.h) {
            		style.height = `${this.dragData.h}px`;
            		if (i.h.indexOf('%') > -1) style.height = (100*v.dragData.h/v.rect.height).toFixed(4) + '%';
            		if (i.t && i.b) i.bottom = ''
            		i.h = style.height;
            	} else {
            		style.height = (100*v.dragData.h/v.rect.height).toFixed(4) + '%';
            		i.h = style.height;
            	}
            	if (i.l) i.r  = '';
            	if (i.t) i.b = '';
            	if (i.r) i.l   = '';
            	if (i.b) i.t    = '';
            	v.styles = v.getStyles(i);
            },
            getStyles(pos) {
        		let style = {};
        		let sw = {width:  pos.w};
        		let sh = {height: pos.h};
        		let st = {top:    pos.t};
        		let sr = {right:  pos.r};
        		let sb = {bottom: pos.b};
        		let sl = {left:   pos.l};
        		if (pos.l && pos.r) {
        			pos.w = '';
        			sw = {};
        		}
        		if (pos.t && pos.b) {
        			pos.h = '';
        			sh = {};
        		}
                Object.assign(style,sw,sh, st,sr,sb,sl);
                return style;
        	},
            handleMoveEnd () {
                this.dragData.dragging = false;
                this.dragData.resizing = false;
                __off(window, 'mousemove', this.handleMoveMove);
                __off(window, 'mouseup', this.handleMoveEnd);
            },
		},
	},
	{
		name: 'Leaf',
		template: `
		<div :class="pclass" class="flex flc" name="Leaf-inst" :level="level" :index="index">
			<div class="h35 w100 bb1c bbx flec pdr5 pdl2" 
				:class="[(selected)?'bgb1':'bgf hovbgf1']" >
				<div :level="level" :style="{'width':(level-1) * 20 + 'px',}" class="flec ofh center">
					<div class="w100 h10 flec bbx pdl10">
						<div class="flex1 bb1c txt"></div>
					</div>
				</div>
				<div class="btn wh20 " :class="[open?'ts90':'ts0']" @click="open=!open">
					<i v-if="value.length" class="fa fa-caret-right"></i>
				</div>
				<div class="flex1 h100 flec btn left ofh"  @click="doAct()" >
					<div class="w100 txt" v-text="title"></div>
				</div>
				<div class="wh25 btn center bgf1 hovbg01" @click="doAddi()"><i class="fa fa-plus"></i></div>
				<div class="wh25 btn center bgf1 hovbg01 marl5" @click="doDeli()"><i class="fa fa-trash"></i></div>
			</div>
			<div class="w100" name="tree" :class="[open?'':'h0 ofh']" :activeId="activeId">
				<Leaf v-for="(v,k) in value" ref="leaf" 
					v-model="v.child" :title="v.f" :pos="v.pos"
					:level="level+1" :index="k" :active="active" 
					:chage="chage ||hasChange" 
					@active="cAct"
					></Leaf>
			</div>
			<div class="w100" name="config"></div>
			<div name="modal">
				<Modal v-model="editModal" @ok="doSaveEdit" @cancel="editModal = false"
					okText = "保存" cancelText="取消" width="500" title="修改">
					<FormData v-model="editItem" class="lh25"></FormData>
				</Modal>
				<Modal v-model="addiModal" @ok="doSaveAddi" @cancel="addiModal = false"
					okText = "保存" cancelText="取消" width="500" title="添加">
					<FormData v-model="editItem" class="lh25"></FormData>
				</Modal>
			</div>
	  	</div>`,
	  	props: {
	  		value: { type: Object,default: {}},
	  		pos:   { type: Object,default: {}},
	  		title: { type: String,default: ''},
	  		class: { type: String,default: ''},
	  		level: { type: Number,default: 0},
	  		index: { type: Number,default: 0},
	  		chage: { type: Number,default: 0},
	  		active:{ type: Object,default: {}},
	  	},
		data: function () {
			return {
				addiModal:false,
				editModal:false,
				tree:[],
				open: false,
				editItem:[],
				dataList:[],
				dataView:[],
				activeId: -1,
				editIndex:-1,
				ids:[],
				hasChange: 1,
			}
		},
		computed: {
			pclass (v = this) {return [v.class]},
			selected () {
				let v = this;
				return (v.active.level==v.level) && (v.active.index==v.index)
			}
		},
		watch: {
			'chage'(v){this.getList(1); },
			'active'(val){
				let v = this;
				// console.log('watch',val.level,val.index,v.level,v.index)
			},
		},
		created: function () {
			let v = this;
			v.getList();
		},
		methods: {
			doAct(){
				let v = this;
				let act = {level: v.level,index:v.index};
				v.$emit('active',act)
			},
			cAct(act){
				let v = this;
				v.$emit('active',act)
			},
			doAddi(ids) {
				let v = this;
				let t = '' + v.title + '-' + (v.value.length + 1);
				let it = [{t:'text',key:'f',k:'组件名称', v: t,},];
				v.editItem = it;
				v.addiModal = true;
				
				// v.value.push(info);
			},
			doDeli(ids) {
				let v = this;
				v.$emit('deli');
			},
			doSaveAddi(){
				let v = this;
				let i = v.editItem;
				let data = {f:'组件',pos:{},child:[]};
				for (let k in i) if (data[i[k].key])  data[i[k].key] = i[k].v;
				v.value.push(data);
				v.addiModal = false;
				v.open = true;
			},
			doSaveDeli(){},
			doSaveEdit(){},
			getList(open){
				let v = this;
			}
		},
	},
	{
		name: 'RouteTree',
		template: `
		<div :class="pclass" class="flex flc" name="RouteTree-inst" >
			<div class="h40 w100"></div>
			<div class="h35 w100 bb1c bbx flec pd05">
				<div class="flex1"></div>
				<div class="w35 h25 btn center tbb cfff hvop08" @click="doAddi"><i class="fa fa-plus"></i></div>
			</div>
			<div class="w100" name="tree">
				<Leaf v-for="(v,k) in dataView" ref="leaf" 
					v-model="v.g.child" :title="v.g.f" :pos="v.g.pos"
					:level="lv + 1" :index="k" :active="active" 
					addi="doAddi" 
					@deli="doDeli(v,k)"
					@active="doAct"></Leaf>
			</div>
			<div class="w100" name="config"></div>
			<div name="RouteTree-modal">
				<Modal v-model="editModal" @ok="doSaveEdit" @cancel="editModal = false"
					okText = "保存" cancelText="取消" width="500" title="修改">
					<FormData v-model="editItem" class="lh25"></FormData>
				</Modal>
				<Modal v-model="addiModal" @ok="doSaveAddi" @cancel="addiModal = false"
					okText = "保存" cancelText="取消" width="500" title="添加">
					<FormData v-model="editItem" class="lh25"></FormData>
				</Modal>
			</div>
	  	</div>`,
	  	props: {
	  		value: { type: Array,default: []},
	  		class: { type: String,default: ''},
	  	},
		data: function () {
			return {
				addiModal:false,
				editModal:false,
				tree:[],
				editItem:[],
				dataList:[],
				dataView:[],
				lv: 0,
				activeId: -1,
				editIndex:-1,
				ids: [],
				active: {level:1,index:-1},
			}
		},
		computed: {
			pclass (v = this) {return [v.class]},
		},
		created: function () {
			let v = this;
			v.getList();
		},
		methods: {
			doAct(act) {
				let v = this;
				v.active = {};
				v.active = __copy(act)
				// console.log('tree active',v.active.level,v.active.index)
			},
			doAddi (kk) {
				let v  = this;
				let lable = '新的页面' + (v.id+1);
				let it = [{t:'text',key:'f',k:'页面名称', v: lable,},];
				v.editItem = it;
				v.addiModal = true;
				console.log('doAddi',it);
			},
			doSaveAddi(v = this,i = v.editItem){
				let data = {a: v.id +1 ,b:1, c:2, d:0, e:0, f:'页面名称', g:''};
				for (let k in i) if (data[i[k].key])  data[i[k].key] = i[k].v;
				__post('api.php?type=page_insert',{action: 'insert',data:data}).then(function(r) {
					if (r.code === 200) {
						v.getList();
						v.addiModal = false;
						__msg(r,data);
					}
				})
			},
			doDeli(i,k) {
				let v = this;
				__confirm('<font color="red">您确定要删除此页面吗？<font>',500000).then((r)=>{
        			console.log('delDataItem');
        			v.doSaveDeli(i);
        		})
			},
			doSaveDeli(i){
				let v = this;
				let data = {where:{eq:{a:i.a}}};
				__post('api.php?type=page_del',{action: 'delete',data:data}).then(function(r) {
					if (r.code === 200) {
						v.getList();
						__msg(r,data);
					}
				})
			},
			doSaveEdit(){},
			getList(){
				let v = this;
				let data = {
					where:{
						eq:{c:2}
					}
				};
				__post('api.php?type=page',{action: 'query',data:data}).then(function(r) {
					let l = r.data;
					let lv= [];
					for (let i in l){
						let it = __copy(l[i]);
						if (it.g) {
							try{
								let s = it.g;
								if (s[0] == '{' || (s[0] == '"' && s[1] == '{')) it.g = JSON.parse(s);
							}catch(e){console.log(e);}
						}
						it.b = it.g.child ? 1 : 0;
						if (!it.b) it.g = {pos:{},f:it.f,child:[]};
						lv.push(it);
					}
					v.dataList = l;
					v.dataView = lv;
					console.log('tree dataView:',lv);
					v.id = r.count;
				})
			}
		},
	},
]
if (!window.widgets) window.widgets = [];
for (let n in __widget) window.widgets.push(__widget[n]);




var default_component = {
	name: 'Default',
	template: `
	<div class="wh100 pr ofh trs2" name="default" :style="{'opacity': opacity}">
		<div name="tool-box" class="pf z2 t0 r5 hovchh30">
			<div class="pdtb5 pd05 hovchh30_ch ofh">
				<div class="wh30 btn bg01 opa5 trs2 hovopa1" @click="openManager = !openManager">
					<i v-if="!openManager" class="fa fa-th-list"></i>
					<i v-else class="fa fa-reply"></i>
				</div>
			</div>
		</div>
		<transition name="slide-fade">
			<div v-if="openManager" name="layout-page" class="pf z1 t0 l0 wh100">
				<div class="wh100 pr flex alc center">
					<Layout v-for="(v,k) in myLayouts" 
						@click="active=k"
						@maxsize="setMaxSize(v,k)" 
						@minsize="setMinSize(v,k)"
						v-model="v" :active="active==k"
						class="lay-item miw101 mih50"></Layout>
				</div>
			</div>
		</transition >
		
		<transition name="slide-fade">
			<div class="wh100 flex flc trs2 pr">
				hello!
			</div>
		</transition >
	</div>`,
	data: function () {
		return {
			opacity: 0,
			id: 1,
			dataList:[],
			dataView:[],
			openManager: false,
			myLayouts:[
				{k:'页面窗口',pos:{t:'5%',l:"4%",w:'60%',h:'90%'},component:'Widgets'},
				{k:'页面管理',pos:{t:'5%',l:"66%",w:'30%',h:'90%'},component:'RouteTree'},
			],
			active:-1,
		}
	},
	created: function () {
		let v = this;
		v.opacity = 1;
	},
	watch:{},
	methods: {
		setMaxSize(i,k) {i.pos = {t:'0%',l:"0%",w:'100%',h:'100%'};},
		setMinSize(i,k) {i.pos = {t:'25%',l:"25%",w:'50%',h:'50%'};},
	},
	
}
const route = [
{
	path: '/index',
	name: 'index',
	component: () => import('../page/index.js')
}, 
{
	path: '/',
	name: 'default',
	component: default_component,
}, 
]

function _start() {
	// 3. 注册组件
	for (let i = 0; i < widgets.length; i++) {Vue.component(widgets[i].name, widgets[i]);};
	for (let i = 0; i < route.length; i++) routes.push(route[i])
	__router = new VueRouter({
		routes: routes
	})
	__router.beforeEach((to, from, next) => {
		log('beforeEach to',to)
		next();
	})
	// 4. 创建和挂载根实例。
	__app = new Vue({
		router: __router,
		data: {
			opacity: 0,
		},
		methods: {
		},
		mounted: function () {
		}
	}).$mount('#app_dom')
	log('start... ')
}

window.addEventListener('load',_start,false);
var __id = 1;
function __getid () {
	let s = '' + Date.now() + Math.random() + __id;
	s = s.replace(".", "_");
	__id++;
	return s;
}
function __post (url, data) {
	// console.log(url)
	if (typeof url == 'object') {
		let t = __copy(url);
		url = t.url;
		data = t.data;
	}
	
	return fetch(url, {
		body: JSON.stringify(data),
		cache: 'no-cache',
		headers: {
			'content-type': 'application/json'
		},
		method: 'POST',
		mode: 'cors',
	}).then(response => response.json()) // parses response to JSON
}
window.__message = function (context, duration, className) {
	
	if ((typeof duration == 'string')) {
		className = duration;
		duration = 5000;
	} else {
		if (!duration) duration = 5000;
	}
	if (!window.__message_list) window.__message_list = [];
	if ((typeof className != 'string')) className = '';
	let dc = function (label, attr) {
	if (!label || (typeof label != 'string')) label = 'div';
		let el = document.createElement(label);
		if (attr && (typeof attr == 'object')) {
			for (let k in attr) {
				let v = attr[k];
				if ((typeof v[0] == 'string') && (typeof v[0] == 'string')) el.setAttribute(v[0],v[1]);
			}
		}
		return el;
	}
	let bcn = '__message_box';
	let box = document.querySelector('.' + bcn);
	if (!box) {
		box = dc('div',[['name',bcn],['class',bcn + ' t0 fs12 w100 z9']])
		box.style.top = '100px'
		document.body.appendChild(box);
	}
	
	let id  = 'm-' + Date.now();
	let msg = dc('div',[['id',id],['class','msg-item-box pf trs3 t0 l0 r0 a z9']]);
	
	let con = dc('div',[['name',id],['class','msg-item-content pr center c666']]);
	let content = dc('div',[['name','msg_text'],['class','text-content pa disi bgf msgshadow br2 pdl15 pdr40 pdtb10 sp1 lh20 bbx trs2 ' + className]]);
	let txt = dc('div',[['name','text'],['class','pr wh100']]);
	let ico = dc('div',[['name','close'],['class','pa t0 r0 w30 h40 hovopa1 opa8 btn sen']]);
	let margin = 30;
	let height = 40;
	let items = document.querySelectorAll('.msg-item-box');
	if (items && items.length) {
		let last = items[items.length - 1];
		let ctx  = last.querySelector('.text-content');
		if (ctx) {
			let atop = parseInt(last.getAttribute('top')) || margin;
			height = (ctx.clientHeight) || height;
			margin = atop + height + 10;
		}
	}
	msg.setAttribute('top',margin)
	msg.style.zIndex = (__transferIndex + 10);
	msg.style.top = '' + (margin - 30) + 'px';
	
	txt.innerHTML = context;
	ico.innerHTML = '<i class="fs10 fa fa-close"></i>';
	content.appendChild(txt)
	content.appendChild(ico)
	con.appendChild(content);
	msg.appendChild(con);
	box.appendChild(msg);
	
	let out = setTimeout(function () {
		msg.style.top = '' + margin + 'px';
		msg.style.opacity = 1;
	},20)
	let updateTop = function () {
		let box = document.querySelector('.__message_box');
		let list = box.querySelectorAll('.msg-item-box');
		if (!list.length) return;
		let marginTop = 30;
		for (let k = 0; k < list.length; k++) {
			let me = list[k];
			if (1) {
				me.style.top = '' + marginTop + 'px';
				me.setAttribute('top',marginTop);
				let ctx  = me.querySelector('.text-content');
				let meHeight = 40;
				if (ctx) { meHeight = (ctx.clientHeight) || meHeight; }
				marginTop = marginTop + meHeight + 10;
			}
		}
	}
	let close = function () {
		let currMargin= parseInt(msg.style.top) || "10px";
		msg.style.top = '' + (currMargin - 20) + 'px';
		msg.style.opacity = 0;
		setTimeout(function () {
			let me = box.querySelector('#' + id);
			if (me) box.removeChild(me);
			updateTop();
			for (let i = 0 ; i < __message_list.length; i++) {
				if (__message_list[i].id == msg.id) __message_list.splice(i,1);
			}
		},200)
	}
	ico.addEventListener('click', close, false);
	out = setTimeout(function () {
		ico.removeEventListener('click', close, false);
		msg.close();
	},duration)
	
	msg.timeout = out;
	msg.close   = close;
	msg.updateTop = updateTop;
	__message_list.push(msg)
	return msg;
}
window.__confirm = function (context,wait) {
	if (!wait || (typeof wait != 'number')) wait = 20000;
	return new Promise(function __cfm(resolve, reject){
		let dc = function (label, attr) {
		if (!label || (typeof label != 'string')) label = 'div';
			let el = document.createElement(label);
			if (attr && (typeof attr == 'object')) {
				for (let k in attr) {
					let v = attr[k];
					if ((typeof v[0] == 'string') && (typeof v[0] == 'string')) el.setAttribute(v[0],v[1]);
				}
			}
			return el;
		}
		let bcn = '__confirm_box';
		let box = document.querySelector('.' + bcn);
		if (!box) {
			box = dc('div',[['name',bcn],['class',bcn + ' t0 fs12 w100']])
			box.style.top = '0px'
			document.body.appendChild(box);
		}
		
		let id  = 'm-' + Date.now();
		let cfm = dc('div',[['id',id],['class','cfm-item-box a pf trs3 t0 l0 r0 b0 flex alc center']]);
		
		let mask = dc('div',[['name',id],['class','cfm-item-content pa wh100 bg03 flex alc center c666']]);
		let content = dc('div',[['name','cfm_text'],['class','text-content pr bgf msgshadow br2 pd015 pdtb10 sp1 lh20 bbx trs2 marb5']]);
		let txt = dc('div',[['name','text'],['class','pr w100 pdr40 pdtb10 txt']]);
		let ico = dc('div',[['name','close'],['class','pa t10 r10 w30 h30 hovopa1 opa8 btn sen bg05']]);
		let okb = dc('div',[['name','ok'],['class','h30 flex alc right mart5']]);
		let btn = dc('div',[['name','btn'],['class','pd05 btn h25 w40 bgcr opa8 hovopa1 trs2 cfff']]);
	
		cfm.style.zIndex = (__transferIndex + 10);
		
		txt.innerHTML = context;
		ico.innerHTML = '<i class="fs10 fa fa-close"></i>';
		btn.innerHTML = '<span >确定</span>';
		content.appendChild(txt)
		content.appendChild(ico)
		content.appendChild(okb)
		okb.appendChild(btn)
		cfm.appendChild(mask);
		cfm.appendChild(content);
		box.appendChild(cfm);

		let close = function () {
			ico.removeEventListener('click', close, false);
			btn.removeEventListener('click', ok, false);
			cfm.style.opacity = 0;
			setTimeout(function () {
				let me = box.querySelector('#' + id);
				if (me) box.removeChild(me);
				reject('a');
			},200)
		}
		let ok = function () {
			ico.removeEventListener('click', close, false);
			btn.removeEventListener('click', ok, false);
			cfm.style.opacity = 0;
			setTimeout(function () {
				let me = box.querySelector('#' + id);
				if (me) box.removeChild(me);
				resolve('a');
			},200)
		}
		ico.addEventListener('click', close, false);
		btn.addEventListener('click', ok, false);
		cfm.close   = close;
		setTimeout(function () {
			cfm.style.opacity = 1;
		},20)
		
		setTimeout(function () {
			let me = box.querySelector('#' + id);
			if (me) box.removeChild(me);
			reject('b');
		},wait)
	})
	return cfm;
}
window.__msg = function (r,data) {
	if (r.count === 1) {
		__message('success','cg');
	} else {
		__message(data.action + ' failed!',10000,'cr');
	}
}

window.__api_info = [
	{
		v: 0,
		k: "固定内容",
	},
]